package com.blog.interceptor;
import com.blog.Utils.DataUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author 任浩
 * @version 1.0
 */

@Component
@Slf4j
public class DataInterceptor implements HandlerInterceptor {

    @Autowired
    private DataUtil dataUtil;
    /**
     * 在每个拦截器里面设置添加访问量的方法。
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("进入Data拦截器");
//        DataUtil dataUtil = new DataUtil();
        //得到当前用户的ip
        String ip = request.getRemoteHost();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh-mm-ss");
        String format = LocalDateTime.now().format(dateTimeFormatter);
        LocalDateTime localDateTime = LocalDate.parse(format,dateTimeFormatter).atStartOfDay();
        dataUtil.setDateTime(localDateTime);
        dataUtil.uvadd(ip); //添加当前访问的独立用户的数据。
        //如果当前用户存在，已经登录，那么就增加日访问用户
        //通过session域里面存储的数据来判断。
        HttpSession session = request.getSession();
        Integer userId = (Integer)session.getAttribute("userId");
        if(userId != null){
            dataUtil.addDau(userId);  //添加日访问量。
        }
        return true;
    }
}
